package com.example.demo.application.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.example.demo.application.dto.UserSaveReq;
import com.example.demo.application.service.IUserAppService;
import com.example.demo.domain.user.dto.UserDto;
import com.example.demo.domain.user.service.IUserService;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class UserAppServiceImpl implements IUserAppService {

	private final IUserService userService = null;

	@Override
	public void saveUser(UserSaveReq userSaveReq) {
		// 1、根据用户名、手机号、邮箱查询用户
		List<UserDto> userList = userService.findByUser(userSaveReq.getUser());
		// 2、检查用户名、手机号是否已经存在
		userSaveReq.getUser().checkUserExist(userList);
		// 3、是否是新增用户
		boolean isAdd = !StringUtils.hasLength(userSaveReq.getUser().getUserId());
		// 4、保存用户
		UserDto user = userService.saveUser(userSaveReq.getUser());
		// 5、删除用户的相关表（组织机构、角色）
		if (!isAdd) {
			// 新增的用户不用删除
			userService.deleteUserRelation(user.getUserId());
		}
		// 6、增加用户的相关表（组织机构、角色）
		userService.addUserRelation(user);
	}

}
